<template>
  <div class="realtime-status-wrap" v-loading="loading">
    <!-- Echarts + 文案 -->
    <template v-if="program==2">
      <div v-for="(item, index) in renderList" :key="index" class="program-wrap">
        <div :id="item.domId" class="echarts-wrap"></div>
        <div class="description-text">
          <p>{{item.fcfName}}</p>
          <p class="result">
            <span :class="item.colorClass">{{item.value}}</span>
            （上阈值：{{item.realMax}}，下阈值：{{item.realMin}}）
          </p>
          <p>{{item.text}}（{{item.units}}）</p>
        </div>
      </div>
    </template>
    <!-- Echarts + 列表 -->
    <template v-else-if="program==3">
      <div v-for="(item, index) in renderList" :key="index" class="program-wrap">
        <template v-if="item.dataTypeId">
          <div :id="item.domId" class="echarts-wrap"></div>
          <div class="description-text">
            <p>{{item.fcfName}}</p>
            <p class="result">
              <span :class="item.colorClass">{{item.value}}</span>
              （上阈值：{{item.realMax}}，下阈值：{{item.realMin}}）
            </p>
            <p>{{item.text}}（{{item.units}}）</p>
          </div>
        </template>
        <template v-else>
          <div class="three-items-warp">
            <p class="three-items-title">{{item.typeName}}</p>
            <p class="three-items-list" v-for="obj in item.tableList" :key="obj.id">
              <span>{{obj.text}}：</span>
              <span>{{obj.value}}</span>
              <span>{{obj.units}}</span>
            </p>
          </div>
        </template>
      </div>
    </template>
    <!-- 图+按钮 -->
    <template v-else-if="program==4">
      <div class="program-wrap">
        <img v-if="imgSrc" :src="imgSrc" class="img-block" />
        <el-button class="video-btn" type="primary" @click="openVideo()">查看监控</el-button>
      </div>
    </template>
    <!-- 图+文案 -->
    <template v-else>
      <div class="program-wrap">
        <img v-if="imgSrc" :src="imgSrc" class="img-block" />
        <div class="description-text">
          <p v-html="description"></p>
        </div>
      </div>
    </template>
    <div v-if="info.hasAnalog == 2 && program != 1" class="program-wrap">
      <img v-if="imgSrc" :src="imgSrc" class="img-block" />
      <div class="description-text">
        <p v-html="description"></p>
      </div>
    </div>
  </div>
</template>
<script>
import { getFacsRealStatusInfo } from '@/api/fcf'
import util from '@/utils/util'

//组合式电气火灾探测器
var dataTypeIdArr = ['30', '31', '32', '33', '34', '35', '36', '37', '38']
export default {
  name: 'RealTimeStatus',
  props: {
    info: {
      required: true,
    },
  },
  data() {
    return {
      loading: true,
      program: 1, // 1-图+文本  2-Echarts+文本  3-Echarts+列表  4-图+按钮
      imgSrc: '',
      description: '',
      fontClass: '',
      baseInfo: {},
      videoInfo: {},
      renderList: [], // 渲染的数据
    }
  },
  created() {
    let that = this
    // 获取实时信息
    getFacsRealStatusInfo({
      fcfId: this.info.id,
      fireTType: this.info.realTimeStatus,
    }).then((res) => {
      that.baseInfo = res.data
      that.dealWith()
    })
  },
  methods: {
    // 处理
    dealWith() {
      let that = this
      let data = {
        realTimeStatus: that.info.realTimeStatus,
        hasAnalog: that.info.hasAnalog,
      }
      let fontClassMap = {
        0: 'color-3',
        10: 'color-1',
        20: 'color-2',
        30: 'color-5',
        40: 'color-8',
      }
      $.extend(data, that.baseInfo)
      // 取值范围：realTimeStatus(0, 10, 20, 30, 40)     hasAnalog(0, 1, 2)
      if (
        data.realTimeStatus == 20 ||
        data.realTimeStatus == 30 ||
        data.realTimeStatus == 40
      ) {
        // 图+文本
        that.program = 1
        that.imgSrc = data.statusPic
        that.description = `<p>${data.fcfName}</p><p class="result ${
          fontClassMap[data.realTimeStatus]
        }">${data.statusAlias}</p>`
      } else {
        if (data.hasAnalog == 1 || data.hasAnalog == 2) {
          let newArr = []
          let hasThreeItems_tempData = false // 标记是否添加过三项-温度数据
          let tempDataIndex = 0
          let hasThreeItems_voltageData = false // 标记是否添加过三项-电压数据
          let voltageDataIndex = 0
          let hasThreeItems_currentData = false // 标记是否添加过三项-电流数据
          let currentDataIndex = 0
          that.program = 2
          for (let i = 0, len = data.analogList.length; i < len; i++) {
            let color = '#77be07'
            let min = 0
            let max = 2.5
            let realMin = ''
            let realMax = ''
            let splitNumber = 5
            let obj = data.analogList[i]
            let newObj = {
              domId: 'echartsWrap_' + obj.id,
              dataTypeId: obj.dataTypeId,
              dataTypeName: obj.dataTypeName,
              fcfName: data.fcfName,
              colorClass: fontClassMap[data.realTimeStatus], // 字体颜色Class
              units: obj.analogUnits, // 计量单位
              text: obj.dataTypeName, // 描述文案
              value: obj.analogValue, // 值
            }
            // Echarts图表
            // 如果存在阈值设置
            if (data.threshold && data.threshold.length > 0) {
              for (let j = 0, num = data.threshold.length; j < num; j++) {
                if (data.threshold[j].dataTypeId == obj.dataTypeId) {
                  min = data.threshold[j].lowerThreshold || 0
                  max = data.threshold[j].upperThreshold || 2.5
                  realMin = data.threshold[j].lowerThreshold
                  realMax = data.threshold[j].upperThreshold
                }
              }
            }
            newObj.realMin = realMin
            newObj.realMax = realMax
            switch (obj.dataTypeId) {
              case 1:
              case 40:
                // 压力/浓度
                newArr.push(newObj)
                // 水压的码表量程一般为0-2.5
                min = 0
                max = 2.5
                // 渲染压力码表
                this.$nextTick(() => {
                  that.drawClockChart(
                    newObj.domId,
                    obj.dataTypeId,
                    newObj.value,
                    newObj.units,
                    min,
                    max,
                    splitNumber
                  )
                })
                break
              case 2:
                let currentAnalogValue = newObj.value
                newArr.push(newObj)
                // 渲染立方体
                this.$nextTick(() => {
                  that.drawWaterChart(
                    newObj.domId,
                    max - currentAnalogValue,
                    currentAnalogValue
                  )
                })
                break
              case 3:
                // 设备电压不展示
                break
              case 5:
                // 温度
                newArr.push(newObj)
                this.$nextTick(() => {
                  that.drawTempClockChart(
                    newObj.domId,
                    obj.dataTypeId,
                    newObj.value,
                    newObj.units,
                    max,
                    data.realTimeStatus
                  )
                })
                break
              case 6:
                // 湿度
                newArr.push(newObj)
                splitNumber = 10
                max = max < 100 ? 100 : max
                this.$nextTick(() => {
                  that.drawClockChart(
                    newObj.domId,
                    obj.dataTypeId,
                    newObj.value,
                    newObj.units,
                    min,
                    max,
                    splitNumber
                  )
                })
                break
              case 7:
              case 8:
              case 9:
                // 电压
                newArr.push(newObj)
                max = 450
                splitNumber = 3
                that.drawHalfClockChart(
                  newObj.domId,
                  obj.dataTypeId,
                  newObj.value,
                  newObj.units,
                  max,
                  splitNumber
                )
                break
              case 10:
              case 11:
              case 12:
                // 电压
                newArr.push(newObj)
                max = 100
                splitNumber = 5
                that.drawHalfClockChart(
                  newObj.domId,
                  obj.dataTypeId,
                  newObj.value,
                  newObj.units,
                  max,
                  splitNumber
                )
                break
              case 30:
              case 31:
              case 32:
                that.program = 3
                if (hasThreeItems_voltageData) {
                  // 已经添加过
                  newArr[voltageDataIndex].tableList.push(newObj)
                } else {
                  // 未添加过
                  hasThreeItems_voltageData = true
                  voltageDataIndex = newArr.length
                  newArr.push({
                    typeName: '电压',
                    tableList: [newObj],
                  })
                }
                break
              case 33:
              case 34:
              case 35:
                that.program = 3

                if (hasThreeItems_currentData) {
                  // 已经添加过
                  newArr[currentDataIndex].tableList.push(newObj)
                } else {
                  // 未添加过
                  hasThreeItems_currentData = true
                  currentDataIndex = newArr.length
                  newArr.push({
                    typeName: '电流',
                    tableList: [newObj],
                  })
                }
                break
              case 36:
              case 37:
              case 38:
                // 三项电流/电压/温度-表格
                that.program = 3

                if (hasThreeItems_tempData) {
                  // 已经添加过
                  newArr[tempDataIndex].tableList.push(newObj)
                } else {
                  // 未添加过
                  hasThreeItems_tempData = true
                  tempDataIndex = newArr.length
                  newArr.push({
                    typeName: '温度',
                    tableList: [newObj],
                  })
                }
                break
              case 39:
                // 三项电流/电压
                that.program = 3
                // 电气火灾剩余电流传感器的放在第一个
                newArr.unshift(newObj)
                tempDataIndex += 1
                voltageDataIndex += 1
                currentDataIndex += 1
                this.$nextTick(() => {
                  that.drawHalfClockChart(
                    newObj.domId,
                    obj.dataTypeId,
                    newObj.value,
                    newObj.units,
                    1000,
                    5
                  )
                })
                break
              default:
                // newArr.push(newObj)
                break
            }
          }
          that.renderList = newArr
          if (data.hasAnalog == 2) {
            that.imgSrc = data.statusPic
            that.description = `<p>${data.fcfName}</p><p class="result ${
              fontClassMap[data.realTimeStatus]
            }">${data.statusAlias}</p>`
          }
        } else {
          if (data.isVideoAnalysis == 1) {
            // 视频：图+按钮
            that.program = 4
            that.imgSrc = data.videoAnalysisPic
            that.videoInfo = data
          } else {
            // 图+文本
            that.program = 1
            that.imgSrc = data.statusPic
            that.description = `<p>${data.fcfName}</p><p class="result ${
              fontClassMap[data.realTimeStatus]
            }">${data.statusAlias}</p>`
          }
        }
      }
      that.loading = false
    },
    // 码表-压力-湿度-浓度
    drawClockChart(
      domId,
      dataTypeId,
      currentAnalogValue,
      currentAnalogUnits,
      min,
      max,
      splitNumber
    ) {
      var self = this
      var _score = currentAnalogValue
      var myChart_safetyIndex = self.$echarts.init(
        document.getElementById(domId)
      )
      var option_safetyIndex = {
        tooltip: null,
        series: [
          {
            type: 'gauge',
            min: min,
            max: max,
            radius: '70%',
            center: ['50%', '50%'],
            splitNumber: splitNumber,
            //仪表盘标题。
            title: {
              show: true,
              textStyle: {
                fontSize: 15,
              },
            },
            axisLabel: {
              //文字样式（及“10”、“20”等文字样式）
              distance: 5, //文字离表盘的距离
              fontSize: 12,
            },
            axisLine: {
              // 坐标轴线
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: [[1, '#000']],
                shadowBlur: 2,
                width: 8,
                shadowColor: '#000', //默认透明
              },
            },
            axisTick: {
              // 坐标轴小标记
              splitNumber: 5,
              length: 14, // 属性length控制线长
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: '#000',
              },
            },
            splitLine: {
              //分割线样式（及10、20等长线样式）
              length: 18,
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: '#000',
              },
            },
            pointer: {
              length: '60%',
              width: '3',
            },
            detail: {
              formatter: currentAnalogUnits,
              textStyle: {
                fontSize: 12,
              },
              offsetCenter: [0, '65%'],
            },
            data: [
              {
                value: _score,
                name: '',
              },
            ],
          },
        ],
      }
      if (option_safetyIndex && typeof option_safetyIndex === 'object') {
        myChart_safetyIndex.setOption(option_safetyIndex, true)
      }
    },
    // echart画水箱
    drawWaterChart(domId, top, bottom) {
      var self = this
      var waterChart = self.$echarts.init(document.getElementById(domId))
      let option = {
        title: null,
        tooltip: {
          show: false,
        },
        xAxis3D: {
          type: 'category',
          data: [''],
        },
        yAxis3D: {
          type: 'category',
          data: [''],
        },
        zAxis3D: {
          type: 'value',
        },
        grid3D: {
          show: false, //是否显示三维迪卡尔坐标
          boxWidth: 80,
          boxDepth: 20,
          axisPointer: {
            show: false,
          },
          viewControl: {
            alpha: 15, //视角绕 x 轴，即上下旋转的角度(与beta一起控制视野成像效果)
            beta: 60, //视角绕 y 轴，即左右旋转的角度
          },
          top: '-5%', //组件的视图离容器上侧的距离
          left: '-10%',
          bottom: '-10%',
        },
        series: [
          {
            type: 'bar3D',
            barSize: 75,
            data: [[0, 0, bottom]],
            stack: 'stack',
            shading: 'lambert',
            itemStyle: {
              //柱条样式
              color: '#428ceb',
              opacity: 0.9,
            },
            emphasis: {
              label: {
                show: false,
              },
            },
          },
          {
            type: 'bar3D',
            barSize: 75,
            data: [[0, 0, top]],
            stack: 'stack',
            shading: 'lambert',
            itemStyle: {
              //柱条样式
              color: '#428ceb',
              opacity: 0.5,
            },
            emphasis: {
              label: {
                show: false,
              },
            },
          },
        ],
      }
      waterChart.setOption(option)
    },
    // 码表-ABC相-电气火灾剩余电流传感器
    drawHalfClockChart(
      domId,
      dataTypeId,
      currentAnalogValue,
      currentAnalogUnits,
      max,
      splitNumber
    ) {
      var self = this
      var myChart_safetyIndex = self.$echarts.init(
        document.getElementById(domId)
      )
      var option_safetyIndex = {
        series: [
          {
            type: 'gauge',
            min: 0,
            max: max,
            radius: '110%',
            center: ['70%', '75%'],
            startAngle: 180,
            endAngle: 90,
            splitNumber: splitNumber, //5等分
            //仪表盘标题。
            title: {
              show: true,
              textStyle: {
                fontSize: 15,
              },
            },
            axisLabel: {
              //文字样式（及“10”、“20”等文字样式）
              distance: 5, //文字离表盘的距离
              fontSize: 12,
            },
            axisLine: {
              // 坐标轴线
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: [[1, '#000']],
                shadowBlur: 2,
                width: 8,
                shadowColor: '#000', //默认透明
              },
            },
            axisTick: {
              // 坐标轴小标记
              splitNumber: 5,
              length: 14, // 属性length控制线长
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: '#000',
              },
            },
            splitLine: {
              //分割线样式（及10、20等长线样式）
              length: 18,
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: '#000',
              },
            },
            pointer: {
              length: '60%',
              width: '3',
            },
            detail: null,
            data: [
              {
                value: currentAnalogValue,
                name: '',
              },
            ],
          },
        ],
      }
      if (option_safetyIndex && typeof option_safetyIndex === 'object') {
        myChart_safetyIndex.setOption(option_safetyIndex, true)
      }
    },
    //码表-温度
    drawTempClockChart(
      domId,
      dataTypeId,
      currentAnalogValue,
      currentAnalogUnits,
      thresholdMax,
      status
    ) {
      var self = this
      var realNum = -25 - currentAnalogValue
      if (realNum <= 0) {
        realNum = Math.abs(realNum)
      }
      let color_bg = '#999'
      let color_green = '#47CFAD'
      let color_red = '#FD5E5E'
      let colorArr = []
      if (status == 0 || currentAnalogValue <= thresholdMax) {
        //被包含
        colorArr.push([Math.abs(realNum / 125), color_green])
        colorArr.push([1, color_bg])
      } else {
        colorArr.push([0, color_bg])
        colorArr.push([Math.abs(realNum / 125), color_red])
        colorArr.push([1, color_bg])
      }
      colorArr.push([1, color_bg])
      var myChart_safetyIndex = self.$echarts.init(
        document.getElementById(domId)
      )
      var option_safetyIndex = {
        series: [
          {
            type: 'gauge',
            min: -25,
            max: 100,
            radius: '70%',
            center: ['50%', '52%'],
            splitNumber: 5,
            //仪表盘标题。
            title: {
              show: true,
              textStyle: {
                fontSize: 15,
              },
            },
            axisLabel: {
              //文字样式（及“10”、“20”等文字样式）
              distance: 5, //文字离表盘的距离
              fontSize: 12,
            },
            axisLine: {
              // 坐标轴线
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: colorArr,
                width: 8,
                // shadowBlur: 2,
                // shadowColor: '#999', //默认透明
              },
            },
            axisTick: {
              // 坐标轴小标记
              splitNumber: 5,
              length: 3, // 属性length控制线长
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: '#fff',
              },
            },
            splitLine: {
              //分割线样式（及10、20等长线样式）
              length: 6,
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: '#fff',
              },
            },
            pointer: {
              length: '60%',
              width: '3',
            },
            detail: {
              formatter: currentAnalogUnits,
              textStyle: {
                fontSize: 12,
              },
              offsetCenter: [0, '65%'],
            },
            data: [
              {
                value: currentAnalogValue,
                name: '',
              },
            ],
          },
        ],
      }
      if (option_safetyIndex && typeof option_safetyIndex === 'object') {
        myChart_safetyIndex.setOption(option_safetyIndex, true)
      }
    },
    // 查看监控
    openVideo() {
      util.rowShowVedio({
        fcFacilitiesId: this.videoInfo.fcfId,
        organizationId: this.info.organizationId,
        serverId: this.info.serverId,
      })
    },
  },
}
</script>
<style lang="scss">
.realtime-status-wrap {
  .program-wrap {
    display: flex;
    align-items: center;
    .echarts-wrap {
      width: 200px;
      height: 200px;
    }
    .img-block {
      width: 200px;
      height: 200px;
    }
    .video-btn {
      margin-left: 15px;
    }
    .three-items-warp {
      padding-left: 20px;
      line-height: 26px;
    }

    .description-text {
      margin-left: 15px;
      line-height: 30px;
      .result {
        font-size: 22px;
      }
    }
  }
}
</style>

